const { DataTypes } = require('sequelize');

module.exports = (sequelize) => {
  const Invitation = sequelize.define('Invitation', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    inviter_id: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
      references: {
        model: 'users',
        key: 'id'
      },
      comment: '邀请人ID'
    },
    invitee_id: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: true,
      references: {
        model: 'users',
        key: 'id'
      },
      comment: '被邀请人ID'
    },
    invite_code: {
      type: DataTypes.STRING(20),
      allowNull: false,
      comment: '邀请码'
    },
    status: {
      type: DataTypes.TINYINT,
      allowNull: false,
      defaultValue: 1,
      comment: '状态: 0-无效, 1-有效'
    },
    register_time: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '注册时间'
    },
    first_consume_time: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '首次消费时间'
    },
    total_reward_points: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      defaultValue: 0,
      comment: '总奖励积分'
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW
    }
  }, {
    tableName: 'invitations',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at'
  });

  // 定义关联关系
  Invitation.associate = (models) => {
    // 邀请人关联
    Invitation.belongsTo(models.User, {
      foreignKey: 'inviter_id',
      as: 'inviter'
    });
    
    // 被邀请人关联
    Invitation.belongsTo(models.User, {
      foreignKey: 'invitee_id',
      as: 'invitee'
    });
  };

  return Invitation;
};
